package com.itheima.canal.listener;


import com.alibaba.otter.canal.protocol.CanalEntry;
import com.itheima.canal.config.RabbitMQConfig;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ZJ
 */
@CanalEventListener
public class SpuListener {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 数据出现改动时进行监听的操作
     * @param eventType 对数据库操作的事件类型
     * @param rowData   对数据库操作的具体数据
     */
    //spu表中数据更改为上架时触发
    @ListenPoint(schema = "changgou_goods",table = {"tb_spu"})
    public void GoodsUp(CanalEntry.EventType eventType,CanalEntry.RowData rowData){
        //更改之前数据
        Map<String,String> orderDate = new HashMap<>();
        rowData.getBeforeColumnsList().forEach((c)->orderDate.put(c.getName(),c.getValue()));
        //更改之后数据
        Map<String,String> newDate = new HashMap<>();
        rowData.getAfterColumnsList().forEach((c)-> newDate.put(c.getName(),c.getValue()));

        //上架操作,判断is_marketable的属性是否从0->1
        if ("0".equals(orderDate.get("is_marketable")) && "1".equals(newDate.get("is_marketable"))){
            //将spuId发送到交换机所对应的队列中
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_UP_EXCHANGE,"",newDate.get("id"));
        }


        //下架操作,判断is_marketable的属性是否从1->0
        if ("1".equals(orderDate.get("is_marketable")) && "0".equals(newDate.get("is_marketable"))){
            //将spuId发送到交换机所对应的队列中
            rabbitTemplate.convertAndSend(RabbitMQConfig.GOODS_DOWN_EXCHANGE,"",newDate.get("id"));
        }

    }
}
